/** 
 * Simplest Librtmp Receive 
 * This program can receive rtmp live stream and save it as local flv file. 
 */  
#include <stdio.h>  
#include <string.h>
#include <stdlib.h>
#include "librtmp/rtmp_sys.h"  
#include "librtmp/log.h"  

int main(int argc, char* argv[])  
{  

	double	duration	=	-1;  
	int		nRead;  
	//is live stream ?  
	int		bLiveStream	=	1;                
	char	url[256];
	int		bufsize	=  64 * 1024;             
	long	countbufsize=0;  
	
	if(argc != 2)
	{
		RTMP_LogPrintf("Useage: ./rtmp_receive <rtmp://>\n");
		return -1;
	}


	strcpy(url, argv[1]);

	char	*buf	=	(char*)malloc(bufsize);  
	memset(buf, 0, bufsize);  

	FILE	*fp		=	fopen("receive.flv","wb");  
	if (!fp){  
		RTMP_LogPrintf("Open File Error.\n");  
		free(buf);
		return -1;  
	}  

	/* set log level */  
	RTMP_LogLevel loglvl = RTMP_LOGDEBUG;  
	RTMP_LogSetLevel(loglvl);  

	RTMP	*rtmp	=	RTMP_Alloc();  
	RTMP_Init(rtmp);  
	//set connection timeout,default 30s  
	rtmp->Link.timeout=10*60;

	if(!RTMP_SetupURL(rtmp, url))  
	{  
		RTMP_Log(RTMP_LOGERROR,"SetupURL Err\n");  
		RTMP_Free(rtmp);  
		return -1;  
	}  
	if (bLiveStream){  
		rtmp->Link.lFlags |= RTMP_LF_LIVE;  
	}  

	//1hour  
	RTMP_SetBufferMS(rtmp, 3600 * 1000);        

	if(!RTMP_Connect(rtmp, NULL)){  
		RTMP_Log(RTMP_LOGERROR, "Connect Err\n");  
		RTMP_Free(rtmp);  
		return -1;  
	}  

	if(!RTMP_ConnectStream(rtmp, 0)){  
		RTMP_Log(RTMP_LOGERROR, "ConnectStream Err\n");  
		RTMP_Close(rtmp);  
		RTMP_Free(rtmp);  
		return -1;  
	}  
	RTMP_LogPrintf("\nstart reading.....\n");
	while(nRead = RTMP_Read(rtmp, buf, bufsize)){  
		fwrite(buf, 1, nRead, fp);  
		countbufsize += nRead;  
		RTMP_LogPrintf("Receive: %5d Bytes,\tTotal: %5.2f kB\n", nRead, countbufsize * 1.0 / 1024);  
	}  

	if(fp)  
		fclose(fp);  

	if(buf){  
		free(buf);  
	}  

	if(rtmp){  
		RTMP_Close(rtmp);  
		RTMP_Free(rtmp);  
		rtmp=NULL;  
	}     
	return 0;  
}  
